package net.neiquan.neiquandemowithkf.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.config.Constant;
import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.easemob.helpdeskdemo.HxConstant;
import com.easemob.helpdeskdemo.HxHelper;
import com.easemob.helpdeskdemo.utils.CommonUtils;

import net.neiquan.neiquandemowithkf.R;
import net.neiquan.neiquandemowithkf.activity.ContainerActivity;
import net.neiquan.neiquandemowithkf.activity.MainActivity;
import net.neiquan.neiquandemowithkf.api.NetUtils;
import net.neiquan.neiquandemowithkf.application.MyApplication;
import net.neiquan.neiquandemowithkf.entity.User;
import net.neiquan.neiquandemowithkf.entity.UserModel;
import net.neiquan.neiquandemowithkf.inter.AppConstant;
import net.neiquan.neiquandemowithkf.utils.Tools;
import net.neiquanlib.base.AppBaseFragment;
import net.neiquanlib.http.NetCallBack;
import net.neiquanlib.http.ResultModel;
import net.neiquanlib.inter.UserEvent;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 作者 ： hjb
 * 时间 ： 2016/7/19.
 */

public class LoginFragment extends AppBaseFragment {
    @InjectView(R.id.account_et)
    EditText mAccountEt;
    @InjectView(R.id.password_et)
    EditText mPasswordEt;

    @Override
    public View initRootView() {
        rootView = mInflater.inflate(R.layout.fragment_login, null);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void setViews() {
        setBackGone();
        setTitleTv("登陆");
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.forget_btn, R.id.login_btn, R.id.register_btn})
    public void onClick(View view) {
        Bundle bundle;
        switch (view.getId()) {
            case R.id.forget_btn:
                bundle = new Bundle();
                bundle.putBoolean(AppConstant.REGISTER, false);
                ContainerActivity.startActivity(getActivity(), RegisterFragment.class, bundle);
                break;
            case R.id.login_btn:
                checkComplete();
                break;
            case R.id.register_btn:
                bundle = new Bundle();
                bundle.putBoolean(AppConstant.REGISTER, true);
                ContainerActivity.startActivity(getActivity(), RegisterFragment.class, bundle);
                break;
        }
    }


    /**
     * 检查信息完整性
     */
    private void checkComplete() {
        if (TextUtils.isEmpty(mAccountEt.getText().toString().trim())) {
            Toast.makeText(getActivity(), "请输入账号", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mPasswordEt.getText().toString().trim())) {
            Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_SHORT).show();
        } else {
            login();
        }
    }

    /**
     * 请求服务器登陆
     */
    private void login() {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().login(mAccountEt.getText().toString().trim(), mPasswordEt.getText().toString().trim(), new NetCallBack() {
            @Override
            public void onSuccess(String message, int errorCode, String response, ResultModel model) {
                Tools.dismissWaitDialog();
                UserModel userModel = model.getModel();
                User user = userModel.getUser();
                user.setUserToken(userModel.getUserToken());
                MyApplication.getInstance().saveUser(user);
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra(MainActivity.TAG, 3);
                startActivity(intent);
                finish();
                EventBus.getDefault().post(new UserEvent(UserEvent.UPDATE_INFO));
                String account = CommonUtils.getRandomAccount();
                if (user != null) {
                    account = TextUtils.isEmpty(user.getNickName()) ? account : user.getNickName();
                }
                final String userPwd = HxConstant.DEFAULT_ACCOUNT_PWD;
                final String finalAccount = account;
                createAccountToServer(account, userPwd, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //登录环信服务器
                                loginHuanxinServer(finalAccount, userPwd);
                            }
                        });
                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }


                });
            }

            @Override
            public void onFail(String message, int errorCode, boolean dataError) {
                Tools.dismissWaitDialog();
                if (!TextUtils.isEmpty(message)) {
                    Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                }
            }
        }, UserModel.class);
    }

    //注册用户
    private void createAccountToServer(final String uname, final String pwd, final EMCallBack callback) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    EMChatManager.getInstance().createAccountOnServer(uname, pwd);
                    if (callback != null) {
                        callback.onSuccess();
                    }
                } catch (EaseMobException e) {
                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.getMessage());
                    }
                }
            }
        });
        thread.start();
    }

    public void loginHuanxinServer(final String uname, final String upwd) {

        // login huanxin server
        EMChatManager.getInstance().login(uname, upwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                HxHelper.getInstance().setCurrentUserName(uname);
                HxHelper.getInstance().setCurrentPassword(upwd);
                try {
                    EMChatManager.getInstance().loadAllConversations();
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
            }
        });
    }

}
